use askama::Template;
use axum::{extract::Query, response::IntoResponse};
use rbatis::PageRequest;
use tower_cookies::Cookies;

use crate::{config::AppContext, domain::topic::Topic, QueryParam, TemplateResponse, TOKEN_NAME};

use super::base::{base, BaseData, Pagination};
use crate::template::filters;

#[derive(Template)]
#[template(path = "index.html")]
pub struct IndexTemplate {
    page: Pagination<Topic>,
    base: BaseData,
}

pub async fn index(cookies: Cookies, page: Query<QueryParam>) -> impl IntoResponse {
    let param = page.0;
    let page_request = PageRequest::new_option(param.page_no, param.page_size);
    let kw = &param.kw.unwrap_or_default();
    let t = &param.t.unwrap_or_default();
    let login = cookies.get(TOKEN_NAME).map_or(false, |_| true);
    let page = Topic::select_page(
        AppContext::rbatis(),
        &page_request,
        kw.as_str(),
        param.c.unwrap_or_default(),
        t.as_str(),
        login,
    )
    .await
    .unwrap();
    let page = Pagination::new(page);
    let mut template = IndexTemplate {
        page: page,
        base: base(cookies).await,
    };
    template.base.c = param.c;
    template.base.kw = Some(kw.clone());
    template.base.t = Some(t.clone());
    TemplateResponse(template)
}
